﻿

namespace HSS.Xaml.UI.Controls
{
	#region Using Directives
	using System;
	using System.Windows;
	using System.Windows.Controls;
	using System.Windows.Controls.Primitives;
	using System.Windows.Input;
	#endregion

	#region AutoCompleteComboBox
	/// <summary>
	/// AutoCompleteComboBox
	/// </summary>
	[TemplatePart(Name = PART_DropDownButtonControl, Type = typeof(ToggleButton))]
	public class AutoCompleteComboBox : AutoCompleteBox
	{
		#region Constants
		/// <summary>
		/// The name of the DropDownButtonControl part
		/// </summary>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "PART")]
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores")]
		public const string PART_DropDownButtonControl = "DropDownButtonControl";
		#endregion

		#region Constructors
		/// <summary>
		/// Constructor
		/// </summary>
		public AutoCompleteComboBox()
		{
			this.DefaultStyleKey = typeof(AutoCompleteComboBox);
			Loaded += (sender, e) => ApplyTemplate();
		}
		#endregion

		#region DropDownButtonControl
		/// <summary>
		/// Gets or sets the ToggleButton
		/// </summary>
		public ToggleButton DropDownButtonControl
		{
			get { return _dropDownButtonControl; }
			set
			{
				if (_dropDownButtonControl != null)
				{
					_dropDownButtonControl.Click -= new RoutedEventHandler(ToggleButton_Click);
					_dropDownButtonControl.MouseEnter -= new MouseEventHandler(ToggleButton_MouseEnter);
					_dropDownButtonControl.MouseLeave -= new MouseEventHandler(ToggleButton_MouseLeave);
				}

				_dropDownButtonControl = value;

				if (_dropDownButtonControl != null)
				{
					_dropDownButtonControl.Click += new RoutedEventHandler(ToggleButton_Click);
					_dropDownButtonControl.MouseEnter += new MouseEventHandler(ToggleButton_MouseEnter);
					_dropDownButtonControl.MouseLeave += new MouseEventHandler(ToggleButton_MouseLeave);
				}
			}

		} ToggleButton _dropDownButtonControl;
		#endregion

		#region Overrides
		/// <summary>
		/// Apply the control template.
		/// </summary>
		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			object child = this.GetTemplateChild(PART_DropDownButtonControl);
			if (null != child)
				this.DropDownButtonControl = child as ToggleButton;
		}
		#endregion

		#region Event Handlers
		void ToggleButton_MouseEnter(object sender, MouseEventArgs e)
		{
			VisualStateManager.GoToState(this, "ToggleButtonOver", true);
		}
		void ToggleButton_MouseLeave(object sender, MouseEventArgs e)
		{
			VisualStateManager.GoToState(this, "ToggleButtonOut", true);
		}
		void ToggleButton_Click(object sender, RoutedEventArgs e)
		{
			if (String.IsNullOrEmpty(this.SearchText))
				this.Text = String.Empty;
			this.IsDropDownOpen = !this.IsDropDownOpen;
		}
		#endregion
	}
	#endregion
}
